import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { Card, Form, Button, Input, Select, Table, Row, Col, message } from "antd";
import { SearchOutlined } from "@ant-design/icons";

import {
  getHosListSearchParamsType,
  hospitalListContentType,
  getProvinceReturnType,
  hospitalListItemsType,
} from "@/api/hospital/model/hospitalListType";

// 1.获取医院列表请求
import {
  getHospitalListRequest,
  getProvinceReturnRequest,
  getCityOrCountyRequest,
  getControlStatusRequest,
} from "@/api/hospital/hospitalList";


export default function HospitalList() {
  const naviGate = useNavigate()
  // 控制数据是否正在加载中
  const [isLoading, setIsLoading] = useState(false);
  // 控制页码
  const [page, setPage] = useState(1);
  // 控制每页条数
  const [limit, setLimit] = useState(3);
  // 控制数据总数
  const [total, setTotal] = useState(10);
  // 查询用户输入的内容
  const [searchParams, setSearchParams] = useState<getHosListSearchParamsType>(
    {}
  );
  //控制表格的数据
  const [hospitalList, setHospitalList] = useState<hospitalListContentType>([]);
  //控制省份数据
  const [province, setProvince] = useState<getProvinceReturnType>([]);
  //根据value获取市级数据
  const [cityS, setCityS] = useState<getProvinceReturnType>([]);
  //根据value获取县或者区级数据
  const [county, setCounty] = useState<getProvinceReturnType>([]);
  //获取医院的等级
  const [hospTypes , setHospTypes] = useState<getProvinceReturnType>([])
  //重新渲染逻辑
  const [anew , setAnew] = useState(true)
  //获取form表单的值
  const [form] = Form.useForm();
  //获取医院列表的数据
  useEffect(() => {
    const getHosListDataHandle = async () => {
      // 控制loading 修改为true
      setIsLoading(true);
      const re = await getHospitalListRequest(page, limit, searchParams);
      
      // 获取对应的数据
      setHospitalList(re.content);
      setTotal(re.totalElements);
      // 控制loading 修改为false
      setIsLoading(false);
    };

    getHosListDataHandle();
  }, [page, limit, searchParams,anew]);
  //获取省份的数据
  useEffect(() => {
    const getProvince = async () => {
      const re = await getProvinceReturnRequest();
      setProvince(re);
    };
    getProvince();
  }, []);
  //获取医院等级
  useEffect(() => {
    const getHosType = async() => {
      const re = await getCityOrCountyRequest('10000')
      setHospTypes(re)
    }
    getHosType()
  },[])

  //事件回调
  //1.根据上一级value获取市数据
  const getCityHandle = async (value: string) => {
    const re = await getCityOrCountyRequest(value);
    setCityS(re);
    //改变省级的时候清空市和县
    form.setFieldsValue({ cityCode: null, districtCode: null });
  };
  //2.根据上一级value获取县数据
  const getCountyHandle = async (value: string) => {
    const re = await getCityOrCountyRequest(value);
    //改变市级的时候县
    form.setFieldsValue({ districtCode: null });
    setCounty(re);
  };

  // 页码的控制
  const clickHandle = (current: number, pageSize: number) => {
    setPage(current);
    setLimit(pageSize);
  };

  // 接收用户输入的值
  const finishHandle = (value: getHosListSearchParamsType) => {
    setSearchParams(value);
  };

  // 查询完重新渲染
  const clearHandle = () => {
    setSearchParams({});
  };

  //点击跳转医院详情
  const goHosListType = (id:string) => {
    return () => {
      naviGate(`/syt/hospital/hospitalShow${id}`)
    }
  }
  //点击修改status
  const btnAlterStatus = (id:string , status:number) => {
    return async () => {
      await getControlStatusRequest(id,status);
      message.success('修改医院状态成功')
      setAnew(!anew)

    }
  }
  //点击跳转医院排班
  const btnSchedule = (hoscode:string) => {
    return () => {
      naviGate(`/syt/hospital/hospitalSchedule/${hoscode}`)
    }
  }
  const columns = [
    {
      title: "序号",
      width: 60,
      dataIndex: "index",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "医院logo",
      dataIndex: "logoData",
      render(logoData: string) {
        return (
          <img width={80} src={`data:image/jpeg;base64,${logoData}`} alt="" />
        );
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "等级",
      render(_: any, data: any) {
        return data.param.hostypeString;
      },
    },
    {
      title: "详细地址",
      render(_: any, data: any) {
        return data.param.fullAddress;
      },
    },
    {
      title: "状态",
      render(_: any, data: any) {
        return data.status === 0 ? "下线" : "上线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      width: 120,
      fixed: "right" as "right",
      dataIndex: "do",
      render(_: any,value: hospitalListItemsType) {
        const {id} = value
        return (
          <div>
            <Button type="primary" onClick={goHosListType(id)}>查看</Button>
            <Button type="primary" onClick={btnSchedule(value.hoscode)}>排班</Button>
            {/* <Button type="primary" onClick={btnAlterStatus}>value.status === 0 ? '上线': '下线'</Button> */}
            {value.status === 0 ? (
              <Button type="primary" onClick={btnAlterStatus(id, 1)}>
                上线
              </Button>
            ) : (
              <Button type="primary" onClick={btnAlterStatus(id, 0)}>
                下线
              </Button>
            )}
          </div>
        );
      },
    },
  ];
  return (
    <div>
      <Card>
        <Form name="basic" form={form} onFinish={finishHandle}>
          <Row gutter={10}>
            <Col span={4}>
              <Form.Item name="provinceCode">
                <Select
                  placeholder="请输入省份"
                  allowClear
                  onChange={getCityHandle}
                >
                  {province.map((item) => {
                    return (
                      <Select.Option value={item.value} key={item.id}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="cityCode">
                <Select
                  placeholder="请输入市"
                  allowClear
                  onChange={getCountyHandle}
                >
                  {cityS.map((item) => {
                    return (
                      <Select.Option value={item.value} key={item.id}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="districtCode">
                <Select placeholder="请输入县/区" allowClear>
                  {county.map((item) => {
                    return (
                      <Select.Option value={item.value} key={item.id}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="hosname">
                <Input placeholder="医院名称" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="hoscode">
                <Input placeholder="医院编号" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="hostype">
                <Select placeholder="医院类型" allowClear>
                {hospTypes.map((item) => {
                    return (
                      <Select.Option value={item.value} key={item.id}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={10}>
            <Col span={4}>
              <Form.Item name="status">
                <Select placeholder="医院状态" allowClear>
                  <Select.Option value={1}>上线</Select.Option>
                  <Select.Option value={0}>下线</Select.Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={2}>
              <Form.Item>
                <Button
                  type="primary"
                  icon={<SearchOutlined />}
                  htmlType="submit"
                >
                  查询
                </Button>
              </Form.Item>
            </Col>
            <Col span={2} style={{ marginLeft: "10px" }}>
              <Form.Item>
                <Button type="default" htmlType="reset" onClick={clearHandle}>
                  清空
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>

        <Table
          style={{ marginTop: "30px" }}
          columns={columns}
          dataSource={hospitalList}
          scroll={{ x: 1100 }}
          bordered
          //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"
          loading={isLoading}
          pagination={{
            //页码的配置：当前页码
            current: page,
            //总数据的数量
            total,
            //每页条数
            pageSize: limit,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [3, 8, 15],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,
            onChange: clickHandle,

            showTotal(total) {
              return `总共有${total}条数据`;
            },
          }}
        />
      </Card>
    </div>
  );
}
